from fastapi import APIRouter, HTTPException
from app.services.user_service import create_user, get_user_by_id,get_users

router = APIRouter()

@router.post("/users/")
async def create_user_api(username: str, email: str, password: str):
    """插入用户的API接口"""
    user = create_user(username, email, password)
    if user:
        return {"message": "用户创建成功", "user_id": user.id}
    else:
        raise HTTPException(status_code=400, detail="用户创建失败")

@router.get("/users/{user_id}")
async def get_user_api(user_id: int):
    """通过用户ID获取用户的API接口"""
    user = get_user_by_id(user_id)
    if user:
        return {"user": {"id": user.id, "username": user.username, "email": user.email}}
    else:
        raise HTTPException(status_code=404, detail="用户未找到")

#获取全部用户
@router.get("/users/")
async def get_users_api():
    """获取全部用户的API接口"""
    users = get_users()
    if users:
        return {"users": [{"id": user.id, "username": user.username, "email": user.email} for user in users]}
    else:
        raise HTTPException(status_code=404, detail="用户未找到")
